import mediapipe as mp
import cv2

class Hands:
    def __init__(self):
        pass

    def process(self, frame):

        # mp_hands = mp.solutions.hands.Hands()
        mp_hands = mp.solutions.hands.Hands()
        # 实例化
        # 将frame的BGR图像转化为RBG图像
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        result = mp_hands.process(frame_rgb)
        hand_landmarks_list = result.multi_hand_landmarks
        if hand_landmarks_list is None:
            return
        landmarks = hand_landmarks_list[0]
        hand_landmarks = landmarks.landmark
        # 连接点
        conns = mp.solutions.hands_connections.HAND_CONNECTIONS
        hand_style = mp.solutions.drawing_utils.DrawingSpec(color=(0, 0, 255), thickness=2)
        conns_style = mp.solutions.drawing_utils.DrawingSpec(color=(0, 0, 0), thickness=2)
        # 进行关键点样式的绘制
        mp.solutions.drawing_utils.draw_landmarks(
            image=frame,
            landmark_list=landmarks,
            connections=conns,
            landmark_drawing_spec=hand_style,
            connection_drawing_spec=conns_style
        )
        # 关键点序号的绘制
        frame_h, frame_w, _ = frame.shape
        for index, lm in enumerate(hand_landmarks):
            x = round(lm.x * frame_w)
            y = round(lm.y * frame_h)
            print(index, x, y)
            cv2.putText(frame, str(index), (x, y), fontFace=cv2.FONT_ITALIC, fontScale=0.4, color=(0, 0, 0),
                        thickness=1)


if __name__ == '__main__':
    mp_hands = Hands()
    cap = cv2.VideoCapture(0)
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        mp_hands.process(frame)
        cv2.imshow('hands', frame)
        key = cv2.waitKey(60)
        if key == ' ':
            break

    cap.release()
    cv2.VideoCapture(0)

